package com.jiaai.cloud.base.configurer;

import org.apache.commons.lang3.StringUtils;
import org.springframework.format.AnnotationFormatterFactory;
import org.springframework.format.Formatter;
import org.springframework.format.Parser;
import org.springframework.format.Printer;

import java.io.Serializable;
import java.security.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashSet;
import java.util.Locale;
import java.util.Set;

public class DateFormatAnnotationFormatterFactory implements AnnotationFormatterFactory<DateFormat> {
    private final Set<Class<?>> fieldTypes;
    private final DateFormatter formatter;
    public static final SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
    public static final SimpleDateFormat format1=new SimpleDateFormat("yyyy/MM/dd");
    public DateFormatAnnotationFormatterFactory() {
        Set<Class<?>> set = new HashSet<Class<?>>();
        set.add(Timestamp.class);
        this.fieldTypes = set;  
        this.formatter = new DateFormatter();
    }


    public Set<Class<?>> getFieldTypes() {
        return fieldTypes;
    }


    public Parser<Date> getParser(DateFormat annotation, Class<?> fieldType) {
        return formatter;  
    }


    public Printer<Date> getPrinter(DateFormat annotation, Class<?> fieldType) {
        return formatter;  
    }

    /**

     */
    private class DateFormatter implements Formatter<Date>,Serializable {
        private static final long serialVersionUID = -818656464607971661L;

        @Override
        public String print(Date date, Locale locale) {
            if(date!=null)
                return format.format(date);
            return null;
        }

        public Date parse(String value, Locale locale) throws ParseException {
           if(StringUtils.isEmpty(value))
               return null;
           else{

               if(value.indexOf("/")>0){
                   return format1.parse(value);
               }else if(value.indexOf("-")>0)
                   return format.parse(value);
               else
                   return null;
           }

        }

    }

}